<?php
/**
 * Created by bianquan
 * CommonUser: ZhuYunlong
 * Email: 920200256@qq.com
 * Date: 2019/1/12
 * Time: 20:07
 */

namespace app\lib\exception;

use think\exception\Handle;
use think\exception\HttpException;
use think\facade\Env;
use think\facade\Log;
use think\facade\Request;
use think\Response;
use Throwable;

/*
 * 重写Handle的render方法，实现自定义异常消息
 */

class CustomExceptionHandler extends Handle
{
    private $code;
    private $message;
    private $errorCode;
    private $data;

    public function render($request, Throwable $e): Response
    {
        if ($e instanceof CustomException) {
            //如果是自定义异常，则控制http状态码，不需要记录日志
            //因为这些通常是因为客户端传递参数错误或者是用户请求造成的异常
            //不应当记录日志
            $this->code = $e->getCode();
            $this->message = $e->getMessage();
            $this->errorCode = $e->errorCode;
            $this->data = $e->data;
        } else {
            // 如果是服务器未处理的异常，将http状态码设置为500，并记录日志
            if (Env::get('app_debug')) {
                // 调试状态下需要显示TP默认的异常页面，因为TP的默认页面
                // 很容易看出问题
                return parent::render($request, $e);
            }

            $this->code = 500;
            $this->message = 'unknown error';
            $this->errorCode = 999;
            $this->recordErrorLog($e);
        }

        $request = Request::instance();
        $result = [
            'msg' => $this->message,
            'error_code' => $this->errorCode,
            'data' => $this->data,
            'request_url' => $request = $request->url()
        ];
        return json($result, $this->code);
    }


    /*
     * 将异常写入日志
     */
    private function recordErrorLog(Throwable $e)
    {
        if (!($e instanceof HttpException)) {
            Log::record($e->getTraceAsString(), 'error');
        }
        Log::record($e->getMessage(), 'error');
    }
}